package com.android.support.lib.universal.sdk.weixin.base;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.android.support.lib.universal.R;
import com.android.support.lib.universal.base.BaseActivity;
import com.android.support.lib.universal.general.Session;
import com.android.support.lib.universal.listenner.BaseListenner;
import com.android.support.lib.universal.sdk.weixin.model.WXuser;
import com.android.support.lib.universal.sdk.weixin.wxapi.Constants;
import com.android.support.lib.universal.util.UtilFastjson;
import com.android.support.lib.universal.util.Utilview;
import com.android.support.lib.universal.view.dialog.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 微信授权登录。要求：注册包名.wxapi.WXEntryActivity(调起微信授权对包名和类名没有要求，但是微信授权回调对包名和类名有要求)
 * 
 * 使用说明：注册包名.wxapi.WXEntryActivity直接继承BaseWXEntryActivity即可。
 * 
 * 跳转到授权界面： Intent intent = new Intent(this, WXEntryActivity.class); Bundle
 * bundle = new Bundle(); // 标识，微信授权登录 bundle.putString("LOGIN", "00");
 * intent.putExtras(bundle); startActivity(intent);
 * 
 * 授权成功后，微信用户信息会保存在Session里。如： WXuser xuser = (WXuser)
 * Session.getSession().get("WXuser"); if (xuser != null) { // 授权成功 }
 *
 * 也可以设置监听接口
 * BaseWXEntryActivity.setListenner(new BaseListenner<WXuser>() {});
 *
 */
public class BaseWXEntryActivity extends BaseActivity implements
		IWXAPIEventHandler {

	//回调接口
	public static BaseListenner<WXuser> listenner;
	//设置回调接口
	public static void setListenner(BaseListenner<WXuser> listenner) {
		BaseWXEntryActivity.listenner = listenner;
	}

	public static String APPID = Constants.APP_ID;
	public static String SECRET = Constants.APP_SECRET;
	private CustomProgressDialog progressDialog;
	IWXAPI api = WXAPIFactory
			.createWXAPI(BaseWXEntryActivity.this, APPID, true);

	@Override
	protected void initUI() {
		// TODO Auto-generated method stub
		setContentView(R.layout.lib_activity_sdk_weixin_logo);
		progressDialog = CustomProgressDialog.createDialog(this);
	}

	@Override
	protected void listenner() {
		// TODO Auto-generated method stub
		// 要使你的程序启动后微信终端能响应你的程序，必须在代码中向微信终端注册你的id
		api.registerApp(APPID);
		// 必不可少，实现IWXAPIEventHandler的回调函数，必须放在程序执行入口
		api.handleIntent(getIntent(), this);
		Intent intent = this.getIntent();
		// 判断是否需要授权登录，防止微信回调后继续授权登陆。
		if (intent.getExtras() != null) {
			Bundle bundle = intent.getExtras();
			if (bundle.getString("LOGIN") != null) {
				SendAuth.Req req = new SendAuth.Req();
				req.scope = "snsapi_userinfo";// 应用授权作用域，如获取用户个人信息则填写snsapi_userinfo
				req.state = "wechat_sdk_demo_test";// 第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
				// 发送微信授权登录请求
				api.sendReq(req);
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			initUI();
			listenner();
		} catch (Exception e) {
			this.finish();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		progressDialog.show();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		// 跳轉到微信界面后，當前界面會被隱藏，故銷毀。
		this.finish();
	}

	// 微信发送的请求将回调到onReq方法
	@Override
	public void onReq(BaseReq req) {
	}

	// 发送到微信请求的响应结果将回调到onResp方法
	@Override
	public void onResp(BaseResp resp) {
		// 微信授权同意
		if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
			String CODE = ((SendAuth.Resp) resp).code;
			String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ APPID
					+ "&secret="
					+ SECRET
					+ "&code="
					+ CODE
					+ "&grant_type=authorization_code";
			GetAccessTokenTask(url);
		} else {
			if(listenner!=null){
				listenner.onFailure(null);
			}
			Utilview.showToastView("微信授权失败");
			this.finish();
		}
	}

	// 获取微信参数
	private void GetAccessTokenTask(String get_user_info_url) {
		HttpUtils httpUtils = new HttpUtils();
		// RequestParams params = new RequestParams();
		httpUtils.send(HttpRequest.HttpMethod.GET, get_user_info_url, null,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						BaseWXEntryActivity.this.finish();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						try {
							JSONObject jsonObject = new JSONObject(result);
							String access_token = jsonObject
									.getString("access_token");
							String openid = jsonObject.getString("openid");
							getWXGetUserInfo(access_token, openid);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	// 获取微信用户信息
	public void getWXGetUserInfo(String access_token, String openid) {
		HttpUtils httpUtils = new HttpUtils();
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
				+ access_token + "&openid=" + openid + "";
		RequestParams params = new RequestParams();

		httpUtils.send(HttpRequest.HttpMethod.GET, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						BaseWXEntryActivity.this.finish();
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							String result = arg0.result;
							WXuser WXuser = UtilFastjson.getEntity(result,
									WXuser.class);
							if(listenner!=null){
								listenner.onSuccess(WXuser);
							}
							// Log.e("test", "用户名：" + WXuser.getNickname());
							// Log.e("test", "头像：" + WXuser.getHeadimgurl());
							// 将微信用户信息保存到Session里。
							Session.getSession().put("WXuser", WXuser);
							BaseWXEntryActivity.this.finish();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
	}

}